from sqlalchemy import create_engine, Column, Integer, String, DateTime, Boolean, ForeignKey, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
import os

# 数据库配置
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./users.db")

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={"check_same_thread": False} if "sqlite" in SQLALCHEMY_DATABASE_URL else {}
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

# 数据库模型
class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(255), unique=True, index=True, nullable=False)
    phone = Column(String(20), nullable=False)
    hospital = Column(String(255), nullable=False)
    position = Column(String(50), nullable=False)
    hashed_password = Column(String(255), nullable=False)
    role = Column(String(20), default="user")  # admin 或 user
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    login_records = relationship("LoginRecord", back_populates="user")
    processing_records = relationship("DataProcessingRecord", back_populates="user")

class LoginRecord(Base):
    __tablename__ = "login_records"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    login_time = Column(DateTime, default=datetime.utcnow, nullable=False)
    ip_address = Column(String(45))  # 支持IPv6
    user_agent = Column(Text)
    status = Column(String(20), default="success")  # success, failed
    
    # 关联关系
    user = relationship("User", back_populates="login_records")

class DataProcessingRecord(Base):
    __tablename__ = "data_processing_records"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    operation_type = Column(String(50), nullable=False)  # 操作类型：image_upload, dicom_process, tdc_analysis等
    operation_details = Column(Text)  # 操作详情的JSON字符串
    file_name = Column(String(255))  # 处理的文件名
    processing_time = Column(DateTime, default=datetime.utcnow, nullable=False)
    duration_ms = Column(Integer)  # 处理耗时（毫秒）
    status = Column(String(20), default="success")  # success, failed, processing
    error_message = Column(Text)  # 错误信息（如果有）
    
    # 关联关系
    user = relationship("User", back_populates="processing_records")

# 依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 